{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n",
        "# Transfer Learning for Computer Vision Tutorial - (for study)\n",
        "**Author**: [Sasank Chilamkurthy](https://chsasank.github.io)\n",
        "\n",
        "In this tutorial, you will learn how to train a convolutional neural network for\n",
        "image classification using transfer learning(迁移学习). You can read more about the transfer\n",
        "learning at [cs231n notes](https://cs231n.github.io/transfer-learning/)_\n",
        "\n",
        "Quoting these notes,\n",
        "\n",
        "    In practice, very few people train an entire Convolutional Network\n",
        "    from scratch (with random initialization), because it is relatively\n",
        "    rare to have a dataset of sufficient size. Instead, it is common to\n",
        "    pretrain a ConvNet on a very large dataset (e.g. ImageNet, which\n",
        "    contains 1.2 million images with 1000 categories), and then use the\n",
        "    ConvNet either as an initialization or a fixed feature extractor for\n",
        "    the task of interest.\n",
        "\n",
        "These two major transfer learning scenarios look as follows:\n",
        "\n",
        "-  **Finetuning the convnet**: Instead of random initialization, we\n",
        "   initialize the network with a pretrained network, like the one that is\n",
        "   trained on imagenet 1000 dataset. Rest of the training looks as\n",
        "   usual.\n",
        "-  **ConvNet as fixed feature extractor**: Here, we will freeze the weights\n",
        "   for all of the network except that of the final fully connected\n",
        "   layer. This last fully connected layer is replaced with a new one\n",
        "   with random weights and only this layer is trained.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# License: BSD\n",
        "# Author: Sasank Chilamkurthy\n",
        "\n",
        "from __future__ import print_function, division\n",
        "\n",
        "import torch\n",
        "import torch.nn as nn\n",
        "import torch.optim as optim\n",
        "from torch.optim import lr_scheduler\n",
        "import torch.backends.cudnn as cudnn\n",
        "import numpy as np\n",
        "import torchvision\n",
        "from torchvision import datasets, models, transforms\n",
        "import matplotlib.pyplot as plt\n",
        "import time\n",
        "import os\n",
        "import copy\n",
        "\n",
        "cudnn.benchmark = True\n",
        "plt.ion()   # interactive mode"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Load Data\n",
        "\n",
        "We will use torchvision and torch.utils.data packages for loading the\n",
        "data.\n",
        "\n",
        "The problem we're going to solve today is to train a model to classify\n",
        "**ants** and **bees**. We have about 120 training images each for ants and bees.\n",
        "There are 75 validation images for each class. Usually, this is a very\n",
        "small dataset to generalize upon, if trained from scratch. Since we\n",
        "are using transfer learning, we should be able to generalize reasonably\n",
        "well.\n",
        "\n",
        "This dataset is a very small subset of imagenet.\n",
        "\n",
        ".. Note ::\n",
        "   Download the data from\n",
        "   [here](https://download.pytorch.org/tutorial/hymenoptera_data.zip)\n",
        "   and extract it to the current directory.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Data augmentation and normalization for training\n",
        "# Just normalization for validation\n",
        "data_transforms = {\n",
        "    'train': transforms.Compose([\n",
        "        transforms.RandomResizedCrop(224),\n",
        "        transforms.RandomHorizontalFlip(),\n",
        "        transforms.ToTensor(),\n",
        "        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n",
        "    ]),\n",
        "    'val': transforms.Compose([\n",
        "        transforms.Resize(256),\n",
        "        transforms.CenterCrop(224),\n",
        "        transforms.ToTensor(),\n",
        "        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n",
        "    ]),\n",
        "}\n",
        "\n",
        "data_dir = 'data/hymenoptera_data'\n",
        "image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),\n",
        "                                          data_transforms[x])\n",
        "                  for x in ['train', 'val']}\n",
        "dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=4,\n",
        "                                             shuffle=True, num_workers=4)\n",
        "              for x in ['train', 'val']}\n",
        "dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}\n",
        "class_names = image_datasets['train'].classes\n",
        "\n",
        "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Visualize a few images\n",
        "Let's visualize a few training images so as to understand the data\n",
        "augmentations.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def imshow(inp, title=None):\n",
        "    \"\"\"Imshow for Tensor.\"\"\"\n",
        "    inp = inp.numpy().transpose((1, 2, 0))\n",
        "    mean = np.array([0.485, 0.456, 0.406])\n",
        "    std = np.array([0.229, 0.224, 0.225])\n",
        "    inp = std * inp + mean\n",
        "    inp = np.clip(inp, 0, 1)\n",
        "    plt.imshow(inp)\n",
        "    if title is not None:\n",
        "        plt.title(title)\n",
        "    plt.pause(0.001)  # pause a bit so that plots are updated\n",
        "\n",
        "\n",
        "# Get a batch of training data\n",
        "inputs, classes = next(iter(dataloaders['train']))\n",
        "\n",
        "# Make a grid from batch\n",
        "out = torchvision.utils.make_grid(inputs)\n",
        "\n",
        "imshow(out, title=[class_names[x] for x in classes])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Training the model\n",
        "\n",
        "Now, let's write a general function to train a model. Here, we will\n",
        "illustrate:\n",
        "\n",
        "-  Scheduling the learning rate\n",
        "-  Saving the best model\n",
        "\n",
        "In the following, parameter ``scheduler`` is an LR scheduler object from\n",
        "``torch.optim.lr_scheduler``.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def train_model(model, criterion, optimizer, scheduler, num_epochs=25):\n",
        "    since = time.time()\n",
        "\n",
        "    best_model_wts = copy.deepcopy(model.state_dict())\n",
        "    best_acc = 0.0\n",
        "\n",
        "    for epoch in range(num_epochs):\n",
        "        print(f'Epoch {epoch}/{num_epochs - 1}')\n",
        "        print('-' * 10)\n",
        "\n",
        "        # Each epoch has a training and validation phase\n",
        "        for phase in ['train', 'val']:\n",
        "            if phase == 'train':\n",
        "                model.train()  # Set model to training mode\n",
        "            else:\n",
        "                model.eval()   # Set model to evaluate mode\n",
        "\n",
        "            running_loss = 0.0\n",
        "            running_corrects = 0\n",
        "\n",
        "            # Iterate over data.\n",
        "            for inputs, labels in dataloaders[phase]:\n",
        "                inputs = inputs.to(device)\n",
        "                labels = labels.to(device)\n",
        "\n",
        "                # zero the parameter gradients\n",
        "                optimizer.zero_grad()\n",
        "\n",
        "                # forward\n",
        "                # track history if only in train\n",
        "                with torch.set_grad_enabled(phase == 'train'):\n",
        "                    outputs = model(inputs)\n",
        "                    _, preds = torch.max(outputs, 1)\n",
        "                    loss = criterion(outputs, labels)\n",
        "\n",
        "                    # backward + optimize only if in training phase\n",
        "                    if phase == 'train':\n",
        "                        loss.backward()\n",
        "                        optimizer.step()\n",
        "\n",
        "                # statistics\n",
        "                running_loss += loss.item() * inputs.size(0)\n",
        "                running_corrects += torch.sum(preds == labels.data)\n",
        "            if phase == 'train':\n",
        "                scheduler.step()\n",
        "\n",
        "            epoch_loss = running_loss / dataset_sizes[phase]\n",
        "            epoch_acc = running_corrects.double() / dataset_sizes[phase]\n",
        "\n",
        "            print(f'{phase} Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}')\n",
        "\n",
        "            # deep copy the model\n",
        "            if phase == 'val' and epoch_acc > best_acc:\n",
        "                best_acc = epoch_acc\n",
        "                best_model_wts = copy.deepcopy(model.state_dict())\n",
        "\n",
        "        print()\n",
        "\n",
        "    time_elapsed = time.time() - since\n",
        "    print(f'Training complete in {time_elapsed // 60:.0f}m {time_elapsed % 60:.0f}s')\n",
        "    print(f'Best val Acc: {best_acc:4f}')\n",
        "\n",
        "    # load best model weights\n",
        "    model.load_state_dict(best_model_wts)\n",
        "    return model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Visualizing the model predictions\n",
        "\n",
        "Generic function to display predictions for a few images\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def visualize_model(model, num_images=6):\n",
        "    was_training = model.training\n",
        "    model.eval()\n",
        "    images_so_far = 0\n",
        "    fig = plt.figure()\n",
        "\n",
        "    with torch.no_grad():\n",
        "        for i, (inputs, labels) in enumerate(dataloaders['val']):\n",
        "            inputs = inputs.to(device)\n",
        "            labels = labels.to(device)\n",
        "\n",
        "            outputs = model(inputs)\n",
        "            _, preds = torch.max(outputs, 1)\n",
        "\n",
        "            for j in range(inputs.size()[0]):\n",
        "                images_so_far += 1\n",
        "                ax = plt.subplot(num_images//2, 2, images_so_far)\n",
        "                ax.axis('off')\n",
        "                ax.set_title(f'predicted: {class_names[preds[j]]}')\n",
        "                imshow(inputs.cpu().data[j])\n",
        "\n",
        "                if images_so_far == num_images:\n",
        "                    model.train(mode=was_training)\n",
        "                    return\n",
        "        model.train(mode=was_training)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Finetuning the convnet\n",
        "\n",
        "Load a pretrained model and reset final fully connected layer.\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "model_ft = models.resnet18(pretrained=True)\n",
        "num_ftrs = model_ft.fc.in_features\n",
        "# Here the size of each output sample is set to 2.\n",
        "# Alternatively, it can be generalized to nn.Linear(num_ftrs, len(class_names)).\n",
        "model_ft.fc = nn.Linear(num_ftrs, 2)\n",
        "\n",
        "model_ft = model_ft.to(device)\n",
        "\n",
        "criterion = nn.CrossEntropyLoss()\n",
        "\n",
        "# Observe that all parameters are being optimized\n",
        "optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)\n",
        "\n",
        "# Decay LR by a factor of 0.1 every 7 epochs\n",
        "exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Train and evaluate\n",
        "\n",
        "It should take around 15-25 min on CPU. On GPU though, it takes less than a\n",
        "minute.\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,\n",
        "                       num_epochs=25)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "visualize_model(model_ft)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## ConvNet as fixed feature extractor\n",
        "\n",
        "Here, we need to freeze all the network except the final layer. We need\n",
        "to set ``requires_grad = False`` to freeze the parameters so that the\n",
        "gradients are not computed in ``backward()``.\n",
        "\n",
        "You can read more about this in the documentation\n",
        "[here](https://pytorch.org/docs/notes/autograd.html#excluding-subgraphs-from-backward)_.\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "model_conv = torchvision.models.resnet18(pretrained=True)\n",
        "for param in model_conv.parameters():\n",
        "    param.requires_grad = False\n",
        "\n",
        "# Parameters of newly constructed modules have requires_grad=True by default\n",
        "num_ftrs = model_conv.fc.in_features\n",
        "model_conv.fc = nn.Linear(num_ftrs, 2)\n",
        "\n",
        "model_conv = model_conv.to(device)\n",
        "\n",
        "criterion = nn.CrossEntropyLoss()\n",
        "\n",
        "# Observe that only parameters of final layer are being optimized as\n",
        "# opposed to before.\n",
        "optimizer_conv = optim.SGD(model_conv.fc.parameters(), lr=0.001, momentum=0.9)\n",
        "\n",
        "# Decay LR by a factor of 0.1 every 7 epochs\n",
        "exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Train and evaluate\n",
        "\n",
        "On CPU this will take about half the time compared to previous scenario.\n",
        "This is expected as gradients don't need to be computed for most of the\n",
        "network. However, forward does need to be computed.\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "model_conv = train_model(model_conv, criterion, optimizer_conv,\n",
        "                         exp_lr_scheduler, num_epochs=25)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "visualize_model(model_conv)\n",
        "\n",
        "plt.ioff()\n",
        "plt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Further Learning\n",
        "\n",
        "If you would like to learn more about the applications of transfer learning,\n",
        "checkout our [Quantized Transfer Learning for Computer Vision Tutorial](https://pytorch.org/tutorials/intermediate/quantized_transfer_learning_tutorial.html).\n",
        "\n",
        "\n",
        "\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.9.9"
    },
    "vscode": {
      "interpreter": {
        "hash": "cf18841ace8313d0bc088ca146c17a6c0040e82121d5cb75c0ea07172309253d"
      }
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
